package com.guodi.model.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.common.utils.PageData;
import com.guodi.core.secure.LoginUser;
import com.guodi.core.secure.utils.AuthUtil;
import com.guodi.map.entity.MapDivision;
import com.guodi.map.feign.IMapClient;
import com.guodi.model.constant.CommonConst;
import com.guodi.model.constant.ModelConst;
import com.guodi.model.entity.MdlFactor;
import com.guodi.model.entity.MdlModel;
import com.guodi.model.entity.MdlModelDir;
import com.guodi.model.entity.MdlModelResult;
import com.guodi.model.mapper.MdlModelResultMapper;
import com.guodi.model.service.IMdlFactorService;
import com.guodi.model.service.IMdlModelDirService;
import com.guodi.model.service.IMdlModelResultService;
import com.guodi.model.service.IMdlModelService;
import com.guodi.model.utils.RecursionUtils;
import com.guodi.system.feign.ISysClient;
import com.guodi.system.vo.OrgVO;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @描述：模型结果表 服务类
 * @作者: 代鹏刚
 * @日期: 2020-06-17
 */
@Slf4j
@Service
public class MdlModelResultServiceImpl extends ServiceImpl<MdlModelResultMapper, MdlModelResult> implements IMdlModelResultService {
    @Resource
    private IMapClient mapClient;
    @Resource
    private ISysClient sysClient;
    @Resource
    private MdlModelResultMapper mdlResultMapper;
    @Resource
    private IMdlModelService iMdlModelService;
    @Resource
    private IMdlFactorService iMdlFactorService;
    @Resource
    private IMdlModelDirService modelDirService;
//    @Resource
//    private IDictClient iDictBizClient;
//    @Resource
//    private IMapClient iMapClient;
    @Resource
    public IMdlModelDirService mdlModelDirService;

    @Override
    public IPage<MdlModelResult> listByEntity(Page page, MdlModelResult mdlModelResult, CommonConst commonConst) {
        LambdaQueryWrapper<MdlModelResult> queryWrapper = (new QueryWrapper()).lambda();
        if(StringUtils.isNotBlank(commonConst.getKeyWord())){
            // queryWrapper.like(MdlModelResult::getName,commonConst.getKeyWord()).or().like(MdlModelResult::getYear,commonConst.getKeyWord());
            queryWrapper.like(MdlModelResult::getName,commonConst.getKeyWord());
        }
        if (StringUtils.isNotBlank(commonConst.getYear())) {
            queryWrapper.eq(MdlModelResult::getYear, commonConst.getYear());
        }
        if(StringUtils.isNotBlank(commonConst.getSortType())){
            if(commonConst.getSortType().equals("1")){
                if(commonConst.getSortMethod().equals("1")){
                    queryWrapper.orderByDesc(MdlModelResult::getCreateTime);
                }else {
                    queryWrapper.orderByAsc(MdlModelResult::getCreateTime);
                }
            }else {
                if(commonConst.getSortMethod().equals("1")){
                    queryWrapper.orderByDesc(MdlModelResult::getYear);
                }else {
                    queryWrapper.orderByAsc(MdlModelResult::getYear);
                }
            }
        }
        return this.page(page,queryWrapper);
    }

    @Override
    public List<MdlModelResult> listByEntity(PageData pd) {
        return mdlResultMapper.listPdByEntity(pd);
    }

    @Override
    public Map<String, Map<String, Object>> statisticalByFactorId(String modelId) {
        // 存储每个因子id对应分析模型结果集合
        Map<String, List<MdlModelResult>> dataMap = new HashMap<>();
        // 获取所有模型集合
        List<MdlModel> allModelList = iMdlModelService.list();
        // 根据模型id查询因子集合
        Map map = new HashMap();
        map.put("model_id",modelId);
        List<MdlFactor> factorList = (List<MdlFactor>)iMdlFactorService.listByMap(map);
        // 获取所有图层集合
        //List<MapLayer> allLayerList = iMapLayerService.listByEntity(null);
        // 根据模型id查询模型结果集合
        for(MdlFactor mdlFactor : factorList){
            if(StringUtils.isNotBlank(mdlFactor.getAnalysisModelId())){
                List<MdlModelResult> mdlModelResults = mdlResultMapper.listByModelIds(mdlFactor.getAnalysisModelId());
                dataMap.put(mdlFactor.getId(),mdlModelResults);
            }
        }
        // 存储返回结果数据集
        Map<String, Map<String, Object>> resultMap = new HashMap<>();
        // 图表索引
        int chartIndex = 0;
        for(String key : dataMap.keySet()){
            chartIndex++;
            // 当前因子对象
            MdlFactor currentFactor = null;
            // 当前因子关联图层对象
            //MapLayer layerPd = null;
            for(MdlFactor factor : factorList){
                if(factor.getId().equals(key)){
                    currentFactor = factor;
                    /*if(StringUtils.isNotBlank(factor.getLayerId())){
                        for(MapLayer mapLayer : allLayerList){
                            if(mapLayer.getId().equals(factor.getLayerId())){
                                layerPd = mapLayer;
                                break;
                            }
                        }
                    }*/
                    break;
                }
            }

            // 存储图表类型对应数据
            Map<String, Object> newMap = new HashMap<String, Object>();
            // 存储年份、数值
            List<String> xAxisList = null, yAxisList = null;
            for(int i = 0; i < dataMap.get(key).size(); i++){
                MdlModelResult result = dataMap.get(key).get(i);
                MdlModel model = null;
                for(MdlModel newModel : allModelList){
                    if(result.getModelIds().contains(newModel.getId())){
                        model = newModel;
                        break;
                    }
                }

                // 柱状图--默认柱状图
                if(true){
                    if(xAxisList == null){
                        xAxisList = new ArrayList<String>();
                        yAxisList = new ArrayList<String>();
                    }
                    if(ModelConst.MODEL_TYPE_FEATURE.equals(model.getType())){
                        JSONObject resultJson = JSONObject.fromObject(result.getResult());
                        JSONObject totalJson = resultJson.getJSONObject(ModelConst.MODEL_LEVEL_ROOTGROUPITEM).getJSONObject(ModelConst.MODEL_STATISTICAL_STATISTICINFORMATION).getJSONObject(ModelConst.MODEL_VALUE_TYPE_CURRENT).getJSONObject(ModelConst.MODEL_FEATURE_FIELD_TOTAL);

                        xAxisList.add(0, result.getYear());
                        yAxisList.add(0, totalJson.getString(ModelConst.MODEL_RASTER_FIELD_AREA + "_Value"));

                        if(i == dataMap.get(key).size()-1){
                            newMap.put("xAxisUnit", "年");
                            newMap.put("yAxisUnit", totalJson.getString(ModelConst.MODEL_RASTER_FIELD_AREA + "_Unit"));
                            newMap.put("xAxisList", xAxisList);
                            newMap.put("yAxisList", yAxisList);
                            newMap.put("factorName", currentFactor.getName());
                            /*if(layerPd != null){
                                newMap.put("layerPd", layerPd);
                            }*/
                            resultMap.put("barChart"+chartIndex, newMap);
                        }
                    }else if(ModelConst.MODEL_TYPE_RASTER.equals(model.getType())){
                        // 饼状图
                        if(!result.getResult().startsWith("[")){
                            result.setResult("["+result.getResult()+"]");
                        }
                        JSONObject resultJson = JSONArray.fromObject(result.getResult()).getJSONObject(0);
                        JSONObject dataJson = resultJson.getJSONObject(ModelConst.MODEL_STATISTICAL_STATISTICINFORMATION);
                        JSONArray statisticalArray = null;
                        if(dataJson.containsKey(ModelConst.MODEL_VALUE_TYPE_CURRENT)){
                            statisticalArray = dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_CURRENT);
                        }else if(dataJson.containsKey(ModelConst.MODEL_VALUE_TYPE_WARN)){
                            statisticalArray = dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_WARN);
                        }else if(dataJson.containsKey(ModelConst.MODEL_VALUE_TYPE_PLAN)){
                            statisticalArray = dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_PLAN);
                        }else if(dataJson.containsKey(ModelConst.MODEL_VALUE_TYPE_TREND)){
                            statisticalArray = dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_TREND);
                        }else {
                            statisticalArray = null;
                        }
                        if(null != statisticalArray){
                            for(int j = 0; j < statisticalArray.size(); j++){
                                JSONObject statisticalJson = statisticalArray.getJSONObject(j);
                                xAxisList.add(statisticalJson.getString(ModelConst.MODEL_RASTER_FIELD_NAME));
                                yAxisList.add(Math.round(statisticalJson.getDouble(ModelConst.MODEL_RASTER_FIELD_AREA)/10000)+"");
                            }
                        }
                        newMap.put("xAxisUnit", "");
                        newMap.put("yAxisUnit", "公顷");
                        newMap.put("xAxisList", xAxisList);
                        newMap.put("yAxisList", yAxisList);
                        newMap.put("factorName", currentFactor.getName());
                        /*if(layerPd != null){
                            newMap.put("layerPd", layerPd);
                        }*/
                        resultMap.put("pieChart"+chartIndex, newMap);
                    }
                }else{
                    // 饼状图
                    JSONObject resultJson = JSONArray.fromObject(result.getResult()).getJSONObject(0);
                    JSONObject dataJson = resultJson.getJSONObject(ModelConst.MODEL_STATISTICAL_STATISTICINFORMATION);
                    if(dataJson.containsKey(ModelConst.MODEL_VALUE_TYPE_CURRENT)){
                        newMap.put("dataList", dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_CURRENT));
                    }else if(dataJson.containsKey(ModelConst.MODEL_VALUE_TYPE_WARN)){
                        newMap.put("dataList", dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_WARN));
                    }else if(dataJson.containsKey(ModelConst.MODEL_VALUE_TYPE_PLAN)){
                        newMap.put("dataList", dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_PLAN));
                    }else{
                        newMap.put("dataList", dataJson.getJSONArray(ModelConst.MODEL_VALUE_TYPE_TREND));
                    }
                    /*if(layerPd != null){
                        newMap.put("layerPd", layerPd);
                    }*/
                    newMap.put("factorName", currentFactor.getName());
                    resultMap.put("pieChart"+chartIndex, newMap);
                }
            }
        }
        return resultMap;
    }

    /**
     * @描述: 根据模型主键统计历年数据
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/19 14:58
     */
    @Override
    public String getHistoryYearData(String modelId) {
        return baseMapper.getHistoryYearData(modelId);
    }

    @Override
    public List<MdlModelResult> findByModelId(String modelId, String year) {
        LambdaQueryWrapper<MdlModelResult> lambdaQueryWrapper = (new QueryWrapper()).lambda();
        lambdaQueryWrapper.like(MdlModelResult::getModelIds,modelId);
        if(StringUtils.isNotBlank(year)){
            lambdaQueryWrapper.eq(MdlModelResult::getYear,year);
        }
        if (!StringUtils.isNotBlank(year)) {
            lambdaQueryWrapper.orderByDesc(MdlModelResult::getYear);
        }
        return list(lambdaQueryWrapper);
    }

    /**
     * @描述: 获取年份->模型结果的映射
     * @入参:
     * @出参:
     * @作者: 余家鑫
     * @日期: 2022/3/11 下午4:40
     */
    private Map<String, MdlModelResult> mapYear2Model(String modelId, List<String> years) {
        if(StringUtils.isBlank(modelId) || CollectionUtils.isEmpty(years)){
            return Collections.emptyMap();
        }
        LambdaQueryWrapper<MdlModelResult> condition = (new QueryWrapper()).lambda();
        condition.like(MdlModelResult::getModelIds,modelId);
        condition.like(MdlModelResult::getModelIds,modelId);
        condition.in(MdlModelResult::getYear, years);
        List<MdlModelResult> list = list(condition);
        if(CollectionUtils.isEmpty(list)){
            return Collections.emptyMap();
        }

        Map<String, MdlModelResult> map = new HashMap<>();
        for (MdlModelResult mdlModelResult : list) {
            map.put(mdlModelResult.getYear(), mdlModelResult);
        }

        return map;
    }

    @Override
    public List<ApiResult> getZhjgByList(List<MdlModelDir> list, String year) {
        MdlModelResult pg = null; // 评估结果
        MdlModelResult zx = null; // 指向
        MdlModelResult yj = null; // 预警结果
        for (MdlModelDir dir : list) {
            LambdaQueryWrapper<MdlModelResult> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(MdlModelResult::getModelIds, dir.getModelId());
            queryWrapper.eq(MdlModelResult::getYear, year);
            MdlModelResult result = this.getOne(queryWrapper);
            if(result != null && "评估结果".equals(dir.getAlias())) {
                pg = result;
            }
            if(result != null && "指向".equals(dir.getAlias())) {
                zx = result;
            }
            if(result != null && "预警结果".equals(dir.getAlias())) {
                yj = result;
            }
        }
        com.alibaba.fastjson.JSONArray pgArray = new com.alibaba.fastjson.JSONArray();
        com.alibaba.fastjson.JSONArray zxArray = new com.alibaba.fastjson.JSONArray();
        com.alibaba.fastjson.JSONArray yjArray = new com.alibaba.fastjson.JSONArray();
        if(pg != null) {
            pgArray = com.alibaba.fastjson.JSONObject.parseObject(pg.getResult()).getJSONObject("RootGroupItem").getJSONArray("SubLevel1GroupItems");
        }
        if(zx != null) {
            zxArray = com.alibaba.fastjson.JSONObject.parseObject(zx.getResult()).getJSONObject("RootGroupItem").getJSONArray("SubLevel1GroupItems");
        }
        if(yj != null) {
            yjArray = com.alibaba.fastjson.JSONObject.parseObject(yj.getResult()).getJSONObject("RootGroupItem").getJSONArray("SubLevel1GroupItems");
        }
        LoginUser user = AuthUtil.getUser();
        String deptId = user.getDeptId();
        com.guodi.core.tool.api.R<OrgVO> dept = sysClient.getOrg(Long.valueOf(deptId));
        String divisionCode = dept.getData().getRegionCode();
        // 查询行政区划树
        List<MapDivision> divisionsTree = RecursionUtils.buildMapDivision(mapClient.listDataByCode(divisionCode.substring(0,2)), "-1");
        if(divisionsTree.size() == 0) {
            throw new RuntimeException("检查一下行政区数据，或者监测字段省级parentCode是不是-1");
        }
        List<ApiResult> resultList = new ArrayList<>();
        List<MapDivision> dzChildrens = divisionsTree.get(0).getChildren();
        // 地州级遍历
        for (int i = 0, is = dzChildrens.size(); i < is; i++) {
            String code = dzChildrens.get(i).getCode();
            ApiResult apiResult = new ApiResult();
            apiResult.setParentCode(dzChildrens.get(i).getParentCode());
            apiResult.setGroupItemCode(code);
            apiResult.setGroupItemName(dzChildrens.get(i).getName());

            com.alibaba.fastjson.JSONObject pg2Object = null;
            com.alibaba.fastjson.JSONObject zx2Object = null;
            com.alibaba.fastjson.JSONObject yj2Object = null;
            for (int j = 0, js = pgArray.size(); j < js; j++) {
                com.alibaba.fastjson.JSONObject object = pgArray.getJSONObject(i);
                if(code.equals(object.getString("GroupItemCode"))) {
                    pg2Object = object;
                    apiResult.setPgStatisticInformation(object.getJSONObject("StatisticInformation"));
                    break;
                }
            }
            for (int j = 0, js = zxArray.size(); j < js; j++) {
                com.alibaba.fastjson.JSONObject object = zxArray.getJSONObject(i);
                if(code.equals(object.getString("GroupItemCode"))) {
                    zx2Object = object;
                    apiResult.setZxStatisticInformation(object.getJSONObject("StatisticInformation"));
                    break;
                }
            }
            for (int j = 0, js = yjArray.size(); j < js; j++) {
                com.alibaba.fastjson.JSONObject object = yjArray.getJSONObject(i);
                if(code.equals(object.getString("GroupItemCode"))) {
                    yj2Object = object;
                    apiResult.setYjStatisticInformation(object.getJSONObject("StatisticInformation"));
                    break;
                }
            }

            List<ApiResult> itemList = new ArrayList<>();
            // 市县级遍历
            List<MapDivision> sxChildrens = dzChildrens.get(i).getChildren();
            for (int j = 0, js = sxChildrens.size(); j < js; j++) {
                String code2 = sxChildrens.get(j).getCode();
                ApiResult apiResultItem = new ApiResult();
                apiResultItem.setParentCode(sxChildrens.get(j).getParentCode());
                apiResultItem.setGroupItemCode(code2);
                apiResultItem.setGroupItemName(sxChildrens.get(j).getName());
                handleSX(apiResultItem, pg2Object, zx2Object, yj2Object);
                itemList.add(apiResultItem);
            }
            apiResult.setChildrens(itemList);
            resultList.add(apiResult);
        }
        // 统计县级结果
        statisticsResult(resultList);
        return resultList;
    }

//    @Override
//    public List<ApiResult> getComprehensiveSupervisionStatisticInfo(ComprehensiveSupervisionModelGetReqVO reqVO) {
//        // 获取模型目录下的第一层子目录
//        LambdaQueryWrapper<MdlModelDir> mdlModelDirCondition = new LambdaQueryWrapper<>();
//        mdlModelDirCondition.eq(MdlModelDir::getParentId, reqVO.getModelDirId());
//        List<MdlModelDir> mdlModelDirs = mdlModelDirService.list(mdlModelDirCondition);
//
//        // 根据年份, 获取评估-指向-预警的模型结果 fixme: 循环查库需要修改
//        Integer year = reqVO.getYear();
//        MdlModelResult pg = null; // 评估结果
//        MdlModelResult zx = null; // 指向
//        MdlModelResult yj = null; // 预警结果
//        com.alibaba.fastjson.JSONObject pgJsonObj = new com.alibaba.fastjson.JSONObject();
//        com.alibaba.fastjson.JSONObject zxJsonObj = new com.alibaba.fastjson.JSONObject();
//        com.alibaba.fastjson.JSONObject yjJsonObj = new com.alibaba.fastjson.JSONObject();
//        for (MdlModelDir dir : mdlModelDirs) {
//            LambdaQueryWrapper<MdlModelResult> queryWrapper = new LambdaQueryWrapper<>();
//            queryWrapper.eq(MdlModelResult::getModelIds, dir.getModelId());
//            queryWrapper.eq(MdlModelResult::getYear, String.valueOf(year));
//            MdlModelResult result = this.getOne(queryWrapper);
//            if(Objects.nonNull(result)) {
//                if(Objects.equals("评估结果", dir.getAlias())){
//                    pg = result;
//                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(pg.getResult());
//                    pgJsonObj = Objects.nonNull(jsonObject) ? jsonObject.getJSONObject("RootGroupItem") : new com.alibaba.fastjson.JSONObject();
//                }
//                if(Objects.equals("指向", dir.getAlias())){
//                    zx = result;
//                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(zx.getResult());
//                    zxJsonObj = Objects.nonNull(jsonObject) ? jsonObject.getJSONObject("RootGroupItem") : new com.alibaba.fastjson.JSONObject();
//                }
//                if(Objects.equals("预警结果", dir.getAlias())){
//                    yj = result;
//                    com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(yj.getResult());
//                    yjJsonObj = Objects.nonNull(jsonObject) ? jsonObject.getJSONObject("RootGroupItem") : new com.alibaba.fastjson.JSONObject();
//                }
//            }
//        }
//
//        // 获取区划信息 + 校验 + 转化为tree
//        String reqDivisionCode = reqVO.getDivisionCode();
//        List<MapDivision> divisions = mapClient.listDataByCode(reqDivisionCode);
//        Optional<MapDivision> divisionEntityOptional = divisions.stream().filter(division -> Objects.equals(division.getCode(), reqDivisionCode)).findFirst();
//        if(!divisionEntityOptional.isPresent()){
//            throw new RuntimeException("找不到区划编码"+ reqDivisionCode + "对应的区划");
//        }
//        MapDivision divisionEntity = divisionEntityOptional.get();
//        List<MapDivision> divisionsTree = Collections.singletonList(divisionEntity);
//        List<MapDivision> childDivisionsTree = RecursionUtils.buildMapDivision(divisions, reqDivisionCode);
//        divisionEntity.setChildren(childDivisionsTree);
//        if(divisionsTree.size() == 0) {
//            throw new RuntimeException("检查一下行政区数据! 根据区划" + reqDivisionCode + "找不到区划树目录");
//        }
//
//        // 返回的结果
//        List<ApiResult> resps = buildComprehensiveSupervisions(divisionsTree, pgJsonObj, zxJsonObj, yjJsonObj);
//        // 由次一级统计第一层的汇总.
//        statisticsResult(resps);
//        return resps;
//    }

    /**
     * @描述: 组装带有层级结构的统计结果查询综合监管汇总情况数据
     * @入参: divisionsTree 区划树结构
     * @入参: pgJsonObj: 评估结果json
     * @入参: zxJsonObj: 指向json
     * @入参: yjJsonObj: 预警结果json
     * @入参: 三个json的结构如下 {"RootGroupItem":{
     *      *         "GroupItemCode":"44",
     *      *         "GroupItemName":"广东省",
     *      *         "GroupItemLevelName":"行政区",
     *      *         "StatisticInformation":{"Warn":{
     *      *                 "健康度低":{
     *      *                     "Area_Value":"946171830.31",
     *      *                     "Area_Unit":"平方米",
     *      *                     "Areapercent_Value":"8.272824217",
     *      *                     "Areapercent_Unit":"%",
     *      *                     "THMJ_Value":"104078901.3341",
     *      *                     "THMJ_Unit":"平方米",
     *      *                     "Count":"20"
     *      *                 }}
     *      *         },
     *      *         "SubLevel1GroupItems":[{结构同RootGroupItem}]}}
     * @出参:
     * @作者: 余家鑫
     * @日期: 2022/3/15 下午2:51
     */
    private List<ApiResult> buildComprehensiveSupervisions(List<MapDivision> divisionsTree, com.alibaba.fastjson.JSONObject pgJsonObj
            , com.alibaba.fastjson.JSONObject zxJsonObj, com.alibaba.fastjson.JSONObject yjJsonObj) {
        List<ApiResult> resps = new ArrayList<>();
        if(CollectionUtils.isEmpty(divisionsTree)){
            return resps;
        }
        // 初始化json, 防止后面空指针
        if(Objects.isNull(pgJsonObj)){
            pgJsonObj = new com.alibaba.fastjson.JSONObject();
        }
        if(Objects.isNull(zxJsonObj)){
            zxJsonObj = new com.alibaba.fastjson.JSONObject();
        }
        if(Objects.isNull(yjJsonObj)){
            yjJsonObj = new com.alibaba.fastjson.JSONObject();
        }

        // 组装
        for (MapDivision division : divisionsTree) {
            String divisionCode = division.getCode();
            ApiResult apiResult = new ApiResult();
            apiResult.setParentCode(division.getParentCode());
            apiResult.setGroupItemCode(divisionCode);
            apiResult.setGroupItemName(division.getName());

            // 评估结果 指向  预警结果的填充
            com.alibaba.fastjson.JSONObject pgRootGroupItem = findRootJsonObj(pgJsonObj, divisionCode);
            com.alibaba.fastjson.JSONObject zxRootGroupItem = findRootJsonObj(zxJsonObj, divisionCode);
            com.alibaba.fastjson.JSONObject yjRootGroupItem = findRootJsonObj(yjJsonObj, divisionCode);
            if(Objects.nonNull(pgRootGroupItem)){
                com.alibaba.fastjson.JSONObject statisticInformation = pgRootGroupItem.getJSONObject("StatisticInformation");
                apiResult.setPgStatisticInformation(statisticInformation);
                String firstWarnKey = getFirstWarnKey(statisticInformation);
                apiResult.setPgjg(firstWarnKey);
            }
            if(Objects.nonNull(zxRootGroupItem)){
                com.alibaba.fastjson.JSONObject statisticInformation = zxRootGroupItem.getJSONObject("StatisticInformation");
                apiResult.setZxStatisticInformation(statisticInformation);
                String firstWarnKey = getFirstWarnKey(statisticInformation);
                apiResult.setZx(firstWarnKey);
            }
            if(Objects.nonNull(yjRootGroupItem)){
                com.alibaba.fastjson.JSONObject statisticInformation = yjRootGroupItem.getJSONObject("StatisticInformation");
                apiResult.setYjStatisticInformation(statisticInformation);
                String firstWarnKey = getFirstWarnKey(statisticInformation);
                apiResult.setYjjg(firstWarnKey);
            }

            List<MapDivision> childrenDivisions = division.getChildren();
            // todo: 这里递归组装子目录
            List<ApiResult> childResps = buildComprehensiveSupervisions(childrenDivisions, pgRootGroupItem, zxRootGroupItem, yjRootGroupItem);
            apiResult.setChildrens(childResps);
            resps.add(apiResult);
        }

        return resps;
    }

    /**
     * @描述: 从 statisticInformation 中获取warn的第一个非 $合计$ 的key
     * @入参: "StatisticInformation":{"Warn":{
     *      *                 "健康度低":{
     *      *                     "Area_Value":"946171830.31",
     *      *                     "Area_Unit":"平方米",
     *      *                     "Areapercent_Value":"8.272824217",
     *      *                     "Areapercent_Unit":"%",
     *      *                     "THMJ_Value":"104078901.3341",
     *      *                     "THMJ_Unit":"平方米",
     *      *                     "Count":"20"
     *      *                 }}
     *      *         }
     * @出参:
     * @作者: 余家鑫
     * @日期: 2022/3/15 下午2:43
     */
    private String getFirstWarnKey(com.alibaba.fastjson.JSONObject statisticInformation) {
        if(Objects.isNull(statisticInformation)){
            return "";
        }
        com.alibaba.fastjson.JSONObject warn = statisticInformation.getJSONObject("Warn");
        if(Objects.nonNull(warn)){
            Iterator keys = warn.keySet().iterator();
            while (keys.hasNext()) {
                String next = (String) keys.next();
                if (!next.equals("$合计$")) {
                    return next;
                }
            }
        }

        return "";
    }


    @Override
    public List<Map<String, Object>> getJczcByList(List<MdlModelDir> list, String year, String division) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (MdlModelDir mdlModelDir : list) {
            Map<String, Object> resultMap = new HashMap<>();
            String name = mdlModelDir.getName();
            List<MdlModelDir> modelDirs = modelDirService.list(new LambdaQueryWrapper<MdlModelDir>().eq(MdlModelDir::getParentId, mdlModelDir.getId()));
            Map<String, Object> map = new HashMap<>();
            map.put("cz", "-");
            map.put("zyhs", "-");
            map.put("czWarn", null);
            map.put("zyhsWarn", null);
            for (MdlModelDir modelDir : modelDirs) {
                LambdaQueryWrapper<MdlModelResult> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(MdlModelResult::getModelIds, modelDir.getModelId());
                queryWrapper.eq(MdlModelResult::getYear, year);
                MdlModelResult modelResult = this.getOne(queryWrapper);
                if(modelResult == null) {
                    break;
                }
                com.alibaba.fastjson.JSONObject root = com.alibaba.fastjson.JSONObject.parseObject(modelResult.getResult()).getJSONObject("RootGroupItem");
                com.alibaba.fastjson.JSONArray jsonArray = root.getJSONArray("SubLevel1GroupItems");
                com.alibaba.fastjson.JSONObject resultJson = null;
                if(division.equals(root.getString("GroupItemCode"))) {
                    resultJson = root;
                }
                if(resultJson == null) {
                    for (int i = 0, is = jsonArray.size(); i < is; i++) {
                        com.alibaba.fastjson.JSONObject jsonObject = jsonArray.getJSONObject(i);
                        if (division.equals(jsonObject.getString("GroupItemCode"))) {
                            resultJson = jsonObject;
                            break;
                        }
                        com.alibaba.fastjson.JSONArray items = jsonObject.getJSONArray("SubLevel1GroupItems");
                        for (int j = 0, js = items.size(); j < js; j++) {
                            com.alibaba.fastjson.JSONObject item = items.getJSONObject(j);
                            if (division.equals(item.getString("GroupItemCode"))) {
                                resultJson = item;
                                break;
                            }
                        }
                    }
                }
                String alias = modelDir.getAlias();
                if(resultJson != null) {
                    if ("超载".equals(alias)) {
                        com.alibaba.fastjson.JSONObject warn = resultJson.getJSONObject("StatisticInformation").getJSONObject("Warn");
                        if (warn != null && warn.size() > 0) {
                            Iterator keys = warn.keySet().iterator();
                            while (keys.hasNext()) {
                                String next = (String) keys.next();
                                if (!next.equals("$合计$")) {
                                    map.put("cz", next);
                                    map.put("czWarn", warn);
                                    break;
                                }
                            }
                        }
                    }
                    if ("资源耗损".equals(alias)) {
                        com.alibaba.fastjson.JSONObject warn = resultJson.getJSONObject("StatisticInformation").getJSONObject("Warn");
                        if (warn != null && warn.size() > 0) {
                            Iterator keys = warn.keySet().iterator();
                            while (keys.hasNext()) {
                                String next = (String) keys.next();
                                if (!next.equals("$合计$")) {
                                    map.put("zyhs", next);
                                    map.put("zyhsWarn", warn);
                                    break;
                                }
                            }
                        }
                    }
                    if ("预警结果".equals(alias)) {
                        map.clear();
                        map.put("yjjg", "-");
                        map.put("yjjgResult", null);
                        com.alibaba.fastjson.JSONObject warn = resultJson.getJSONObject("StatisticInformation").getJSONObject("Warn");
                        if (warn != null && warn.size() > 0) {
                            Iterator keys = warn.keySet().iterator();
                            while (keys.hasNext()) {
                                String next = (String) keys.next();
                                if (!next.equals("$合计$")) {
                                    map.put("yjjg", next);
                                    map.put("yjjgResult", resultJson);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            resultMap.put("name", name);
            resultMap.put("result", map);
            resultList.add(resultMap);
        }
        return resultList;
    }

//    @Override
//    public DynamicEvaluationModelGetRespDTO getDynamicEvaluationStatisticInfo(DynamicEvaluationModelGetReqVO reqVO) {
//        String divisionCode = reqVO.getDivisionCode();
//        String divisionName = iMapClient.getNameByCode(divisionCode);
//        if(StringUtils.isEmpty(divisionName)){
//            throw new ServiceException("根据区划编码找不到对应的区划名字, divisionCode = " + divisionCode);
//        }
//
//        // 校验字典编码列表值
//        String dictBizCode = reqVO.getDictBizCode();
//        R<List<DictBiz>> dictBizsR = iDictBizClient.getList(dictBizCode);
//        if(Objects.isNull(dictBizsR) || !dictBizsR.isSuccess() || CollectionUtils.isEmpty(dictBizsR.getData())){
//            throw new ServiceException("根据业务字典编码无法找到对应的数据, dictBizCode = " + dictBizCode);
//        }
//        List<DictBiz> dictBizs = dictBizsR.getData();
//
//        // 获取近三年的模型数据 todo: 近三年 = 传入的年份前一年和后一年以及传入的年份 总共三年
//        String modelId = reqVO.getModelId();
//        Integer year = reqVO.getYear();
//        List<String> nearly3Years = Arrays.asList(String.valueOf(year - 1), String.valueOf(year), String.valueOf((year + 1)));
//        Map<String, MdlModelResult> year2ModelResuleMap = mapYear2Model(modelId, nearly3Years);
//
//        // todo: 组装近三年的数据
//        List<DynamicEvaluationModelGetRespDTO.YearData> nearly3YearDatas = buildNearly3YearDatas(divisionCode, dictBizs, nearly3Years, year2ModelResuleMap);
//
//        // 获取该年, 该区划, 下一级孩子的数据汇总 和 超载情况
//        List<DynamicEvaluationModelGetRespDTO.DivisionData> divisionDatas = null;
//        OverloadCondition overloadCondition = null;
//        MdlModelResult currYearModelResult = year2ModelResuleMap.get(String.valueOf(year));
//        if(Objects.nonNull(currYearModelResult) && StringUtils.isNotBlank(currYearModelResult.getResult())){
//            com.alibaba.fastjson.JSONObject resultJsonObj = com.alibaba.fastjson.JSONObject.parseObject(currYearModelResult.getResult());
//            com.alibaba.fastjson.JSONObject rootGroupItem = findRootJsonObj(resultJsonObj.getJSONObject("RootGroupItem"), divisionCode);
//            // 指定区划是否存在
//            if(Objects.nonNull(rootGroupItem)) {
//                // todo: 获取该年, 该区划, 下一级孩子的数据汇总
//                divisionDatas = buildDivisionDatas(dictBizs, rootGroupItem);
//                // todo: 获取超载情况
//                overloadCondition = buildOverloadCondition(rootGroupItem, dictBizs);
//            }
//
//        }
//
//        // 组装返回体
//        DynamicEvaluationModelGetRespDTO resp = new DynamicEvaluationModelGetRespDTO();
//        resp.setNearly3YearDatas(nearly3YearDatas);
//        resp.setDivisionDatas(CollectionUtils.isEmpty(divisionDatas) ? Collections.emptyList() : divisionDatas);
//        resp.setOverloadCondition(Objects.isNull(overloadCondition) ? OverloadCondition.getEmptyInstance(divisionCode, divisionName) : overloadCondition);
//        return resp;
//    }


//    /**
//     * @描述: 获取该年, 该区划, 下一级孩子的数据汇总
//     * @入参:
//     * @出参:
//     * @作者: 余家鑫
//     * @日期: 2022/3/14 上午10:22
//     */
//    private List<DynamicEvaluationModelGetRespDTO.DivisionData> buildDivisionDatas(List<DictBiz> dictBizs, com.alibaba.fastjson.JSONObject rootGroupItem) {
//        if(CollectionUtils.isEmpty(dictBizs)){
//            return Collections.emptyList();
//        }
//        if(Objects.isNull(rootGroupItem)){
//            return Collections.emptyList();
//        }
//
//        List<DynamicEvaluationModelGetRespDTO.DivisionData> divisionDatas = new ArrayList<>();
//        com.alibaba.fastjson.JSONArray subLevel1GroupItems = rootGroupItem.getJSONArray("SubLevel1GroupItems");
//        // 孩子节点不为空
//        if(!CollectionUtils.isEmpty(subLevel1GroupItems)){
//            for (int i = 0, size = subLevel1GroupItems.size(); i < size; i++) {
//                com.alibaba.fastjson.JSONObject groupItem = subLevel1GroupItems.getJSONObject(i);
//                if(Objects.isNull(groupItem)){
//                    continue;
//                }
//
//                com.alibaba.fastjson.JSONObject statisticInformation = groupItem.getJSONObject("StatisticInformation");
//                // 判断统计值是否不为空
//                if(Objects.isNull(statisticInformation) || Objects.isNull(statisticInformation.getJSONObject("Warn"))){
//                    continue;
//                }
//
//                // 统计数据
//                List<StatisticInfo> statisticInfos = new ArrayList<>();
//                com.alibaba.fastjson.JSONObject warn = statisticInformation.getJSONObject("Warn");
//                for (DictBiz dictBiz : dictBizs) {
//                    String dictValue = dictBiz.getDictValue();
//                    com.alibaba.fastjson.JSONObject warnItem = warn.getJSONObject(dictValue);
//                    StatisticInfo statisticInfo = new StatisticInfo();
//                    statisticInfo.setName(dictValue);
//                    statisticInfo.setValue(Objects.nonNull(warnItem) ? warnItem.getOrDefault("Count", "").toString() : "0");
//                    statisticInfos.add(statisticInfo);
//                }
//
//                // 填充
//                DynamicEvaluationModelGetRespDTO.DivisionData divisionData = new DynamicEvaluationModelGetRespDTO.DivisionData();
//                divisionData.setDivisionCode(groupItem.getOrDefault("GroupItemCode", "").toString());
//                divisionData.setDivisionName(groupItem.getOrDefault("GroupItemName", "").toString());
//                divisionData.setStatisticInfos(statisticInfos);
//                divisionDatas.add(divisionData);
//            }
//        }
//
//        return divisionDatas;
//    }


//    /**
//     * @描述: 组装近三年的数据
//     * @入参:
//     * @出参:
//     * @作者: 余家鑫
//     * @日期: 2022/3/14 上午10:05
//     */
//    private List<DynamicEvaluationModelGetRespDTO.YearData> buildNearly3YearDatas(String divisionCode, List<DictBiz> dictBizs, List<String> nearly3Years, Map<String, MdlModelResult> year2ModelResuleMap) {
//        List<DynamicEvaluationModelGetRespDTO.YearData> nearly3YearDatas = new ArrayList<>();
//        for (String nearly3Year : nearly3Years) {
//            DynamicEvaluationModelGetRespDTO.YearData yearData = new DynamicEvaluationModelGetRespDTO.YearData();
//            yearData.setYear(nearly3Year);
//
//            // 组装该年份的统计数据
//            MdlModelResult mdlModelResult = year2ModelResuleMap.get(nearly3Year);
//            List<StatisticInfo> statisticInfos = null;
//            // 判断返回的模型结果是否为空
//            if(Objects.nonNull(mdlModelResult) && StringUtils.isNotBlank(mdlModelResult.getResult())){
//                com.alibaba.fastjson.JSONObject resultJsonObj = com.alibaba.fastjson.JSONObject.parseObject(mdlModelResult.getResult());
//                com.alibaba.fastjson.JSONObject rootGroupItem = findRootJsonObj(resultJsonObj.getJSONObject("RootGroupItem"), divisionCode);
//
//                // 判断从模型结果里面拿到的数据, 是否找得到符合传入的区划的数据
//                if(Objects.nonNull(rootGroupItem)){
//                    com.alibaba.fastjson.JSONObject statisticInformation = rootGroupItem.getJSONObject("StatisticInformation");
//
//                    // 判断统计值是否不为空
//                    if(Objects.nonNull(statisticInformation) && Objects.nonNull(statisticInformation.getJSONObject("Warn"))){
//                        statisticInfos = new ArrayList<>();
//                        com.alibaba.fastjson.JSONObject warn = statisticInformation.getJSONObject("Warn");
//                        for (DictBiz dictBiz : dictBizs) {
//                            String dictValue = dictBiz.getDictValue();
//                            com.alibaba.fastjson.JSONObject warnItem = warn.getJSONObject(dictValue);
//                            StatisticInfo statisticInfo = new StatisticInfo();
//                            statisticInfo.setName(dictValue);
//                            statisticInfo.setValue(Objects.nonNull(warnItem) ? warnItem.getOrDefault("Count", "").toString() : "0");
//                            statisticInfos.add(statisticInfo);
//                        }
//                    }
//                }
//            }
//
//            // 填充默认值
//            if(Objects.isNull(statisticInfos)){
//                statisticInfos = listZeroStatisticInfos(dictBizs);
//            }
//            yearData.setStatisticInfos(statisticInfos);
//
//            nearly3YearDatas.add(yearData);
//        }
//        return nearly3YearDatas;
//    }
//
//
//    /**
//     * @描述: 组装过载情况
//     * @入参:
//     * @出参:
//     * @作者: 余家鑫
//     * @日期: 2022/3/11 下午3:42
//     */
//    private OverloadCondition buildOverloadCondition(com.alibaba.fastjson.JSONObject rootGroupItem, List<DictBiz> dictBizs) {
//
//        OverloadCondition overloadCondition = new OverloadCondition();
//        overloadCondition.setDivisionCode(rootGroupItem.getOrDefault("GroupItemCode", "").toString());
//        overloadCondition.setDivisionName(rootGroupItem.getOrDefault("GroupItemName", "").toString());
//
//        // 填充当前级别的统计信息
//        List<StatisticInfo> statisticInfos = null;
//        com.alibaba.fastjson.JSONObject statisticInformation = rootGroupItem.getJSONObject("StatisticInformation");
//        // 如果json中的统计值为空, 填充默认值
//        if(Objects.isNull(statisticInformation) || Objects.isNull(statisticInformation.getJSONObject("Warn"))){
//            statisticInfos = listZeroStatisticInfos(dictBizs);
//        } else {
//            statisticInfos = new ArrayList<>();
//            com.alibaba.fastjson.JSONObject warn = statisticInformation.getJSONObject("Warn");
//            for (DictBiz dictBiz : dictBizs) {
//                String dictValue = dictBiz.getDictValue();
//                com.alibaba.fastjson.JSONObject warnItem = warn.getJSONObject(dictValue);
//                StatisticInfo statisticInfo = new StatisticInfo();
//                statisticInfo.setName(dictValue);
//                statisticInfo.setValue(Objects.nonNull(warnItem) ? warnItem.getOrDefault("Count", "").toString() : "0");
//                statisticInfos.add(statisticInfo);
//
//            }
//        }
//        overloadCondition.setStatisticInfos(statisticInfos);
//
//        // 递归填充孩子节点
//        List<OverloadCondition> children = new ArrayList<>();
//        fillOverloadConditions(children, rootGroupItem.getJSONArray("SubLevel1GroupItems"), dictBizs);
//        overloadCondition.setChildren(children);
//
//        return overloadCondition;
//    }
//
//    /**
//     * @描述: 填充children
//     * @入参:
//     * @出参:
//     * @作者: 余家鑫
//     * @日期: 2022/3/11 下午3:33
//     */
//    private List<OverloadCondition> fillOverloadConditions(List<OverloadCondition> overloadConditions
//            , com.alibaba.fastjson.JSONArray groupItems, List<DictBiz> dictBizs) {
//        if(CollectionUtils.isEmpty(groupItems)){
//            return overloadConditions;
//        }
//
//        for (int i = 0, size = groupItems.size(); i < size; i++) {
//            com.alibaba.fastjson.JSONObject groupItem = groupItems.getJSONObject(i);
//            if(Objects.isNull(groupItem)){
//                continue;
//            }
//
//            OverloadCondition overloadCondition = buildOverloadCondition(groupItem, dictBizs);
//            overloadConditions.add(overloadCondition);
//        }
//
//        return overloadConditions;
//    }
//
//    /**
//     * @描述: 获取零值的统计信息
//     * @入参:
//     * @出参:
//     * @作者: 余家鑫
//     * @日期: 2022/3/11 下午3:21
//     */
//    private List<StatisticInfo> listZeroStatisticInfos(List<DictBiz> dictBizs) {
//        if(CollectionUtils.isEmpty(dictBizs)){
//            return Collections.emptyList();
//        }
//
//        List<StatisticInfo> statisticInfos = new ArrayList<>();
//        for (DictBiz dictBiz : dictBizs) {
//            StatisticInfo statisticInfo = new StatisticInfo();
//            statisticInfo.setName(dictBiz.getDictValue());
//            statisticInfo.setValue("0");
//            statisticInfos.add(statisticInfo);
//        }
//
//        return statisticInfos;
//    }


    /**
     * @描述: 根据条件, 找到根节点json, 通过
     * @入参: groupItem, 符合条件的 "RootGroupItem":{
     *         "GroupItemCode":"44",
     *         "GroupItemName":"广东省",
     *         "GroupItemLevelName":"行政区",
     *         "StatisticInformation":{"Warn":{
     *                 "健康度低":{
     *                     "Area_Value":"946171830.31",
     *                     "Area_Unit":"平方米",
     *                     "Areapercent_Value":"8.272824217",
     *                     "Areapercent_Unit":"%",
     *                     "THMJ_Value":"104078901.3341",
     *                     "THMJ_Unit":"平方米",
     *                     "Count":"20"
     *                 }}
     *         },
     *         "SubLevel1GroupItems":[{结构同RootGroupItem}]} 的json数据
     * @入参: divisionCode 根区划的编码
     * @出参: 同入参的结构. 只是根为divisionCode
     * @作者: 余家鑫
     * @日期: 2022/3/11 下午2:58
     */
    private com.alibaba.fastjson.JSONObject findRootJsonObj(com.alibaba.fastjson.JSONObject groupItem, String divisionCode) {
        if(Objects.isNull(groupItem)){
            return null;
        }

        String groupItemCode = groupItem.getString("GroupItemCode");
        if(Objects.equals(divisionCode, groupItemCode)){
            return groupItem;
        }

        // 递归从下级查询
        com.alibaba.fastjson.JSONArray subLevel1GroupItems = groupItem.getJSONArray("SubLevel1GroupItems");
        if(CollectionUtils.isEmpty(subLevel1GroupItems)){
            return null;
        }
        for (int i = 0, size = subLevel1GroupItems.size(); i < size; i++) {
            com.alibaba.fastjson.JSONObject subLevel1GroupItem = subLevel1GroupItems.getJSONObject(i);
            com.alibaba.fastjson.JSONObject temp = findRootJsonObj(subLevel1GroupItem, divisionCode);
            if(Objects.nonNull(temp)){
                return temp;
            }
        }

        return null;
    }

    /**
     * @作者: 林楷 2021/10/28
     * @描述: 处理县级模型结果数据
     * @参数:
     * @返回:
     */
    private void handleSX(ApiResult apiResultItem, com.alibaba.fastjson.JSONObject pg2Object, com.alibaba.fastjson.JSONObject zx2Object, com.alibaba.fastjson.JSONObject yj2Object) {
        com.alibaba.fastjson.JSONObject pg3Object = null;
        com.alibaba.fastjson.JSONObject zx3Object = null;
        com.alibaba.fastjson.JSONObject yj3Object = null;
        String code2 = apiResultItem.getGroupItemCode();
        if(pg2Object != null) {
            com.alibaba.fastjson.JSONArray pg3Array = pg2Object.getJSONArray("SubLevel1GroupItems");
            for (int k = 0, ks = pg3Array.size(); k < ks; k++) {
                if(code2.equals(pg3Array.getJSONObject(k).getString("GroupItemCode"))){
                    pg3Object = pg3Array.getJSONObject(k);
                    break;
                }
            }
        }
        if(zx2Object != null) {
            com.alibaba.fastjson.JSONArray zx3Array = zx2Object.getJSONArray("SubLevel1GroupItems");
            for (int k = 0, ks = zx3Array.size(); k < ks; k++) {
                if(code2.equals(zx3Array.getJSONObject(k).getString("GroupItemCode"))){
                    zx3Object = zx3Array.getJSONObject(k);
                    break;
                }
            }
        }
        if(yj2Object != null) {
            com.alibaba.fastjson.JSONArray yj3Array = yj2Object.getJSONArray("SubLevel1GroupItems");
            for (int k = 0, ks = yj3Array.size(); k < ks; k++) {
                if(code2.equals(yj3Array.getJSONObject(k).getString("GroupItemCode"))){
                    yj3Object = yj3Array.getJSONObject(k);
                    break;
                }
            }
        }

        if(pg3Object != null) {
            apiResultItem.setPgStatisticInformation(pg3Object.getJSONObject("StatisticInformation"));
            com.alibaba.fastjson.JSONObject pgWarn = pg3Object.getJSONObject("StatisticInformation").getJSONObject("Warn");
            if(pgWarn != null && pgWarn.size() > 0) {
                Iterator keys = pgWarn.keySet().iterator();
                while (keys.hasNext()) {
                    String next = (String) keys.next();
                    if (!next.equals("$合计$")) {
                        apiResultItem.setPgjg(next);
                        break;
                    }
                }
            }
        }
        if(zx3Object != null) {
            apiResultItem.setZxStatisticInformation(zx3Object.getJSONObject("StatisticInformation"));
            com.alibaba.fastjson.JSONObject zxWarn = zx3Object.getJSONObject("StatisticInformation").getJSONObject("Warn");
            if(zxWarn != null && zxWarn.size() > 0) {
                Iterator keys = zxWarn.keySet().iterator();
                while (keys.hasNext()) {
                    String next = (String) keys.next();
                    if (!next.equals("$合计$")) {
                        apiResultItem.setZx(next);
                        break;
                    }
                }
            }
        }
        if(yj3Object != null) {
            apiResultItem.setYjStatisticInformation(yj3Object.getJSONObject("StatisticInformation"));
            com.alibaba.fastjson.JSONObject yjWarn = yj3Object.getJSONObject("StatisticInformation").getJSONObject("Warn");
            if(yjWarn != null && yjWarn.size() > 0) {
                Iterator keys = yjWarn.keySet().iterator();
                while (keys.hasNext()) {
                    String next = (String) keys.next();
                    if (!next.equals("$合计$")) {
                        apiResultItem.setYjjg(next);
                        break;
                    }
                }
            }
        }
    }
    /**
     * @作者: 林楷 2021/10/28
     * @描述: 统计县级结果
     * @参数:
     * @返回:
     */
    private void statisticsResult(List<ApiResult> resultList) {
        String pgTitle = null;
        String zxTitle = null;
        String yjTitle = null;
        for (ApiResult result : resultList) {
            List<ApiResult> items = result.getChildrens();
            for (ApiResult itemm : items) {
                if(itemm.getPgjg().indexOf("压力") >= 0) {
                    pgTitle = "压力大";
                }
                if(itemm.getPgjg().indexOf("超载") >= 0) {
                    pgTitle = "超载";
                }
                if(itemm.getPgjg().indexOf("超标") >= 0) {
                    pgTitle = "超标";
                }
                if(itemm.getPgjg().indexOf("健康") >= 0) {
                    pgTitle = "健康度低";
                }
                if(itemm.getZx().indexOf("变化") >= 0) {
                    zxTitle = "变化趋差";
                }
                if(itemm.getYjjg().indexOf("警区") >= 0) {
                    yjTitle = "红色预警区";
                }
            }
            if(pgTitle != null && zxTitle != null && yjTitle != null) {
                break;
            }
        }
        for (ApiResult result : resultList) {
            List<ApiResult> items = result.getChildrens();
            int pgCount = 0;
            int zxCount = 0;
            int yjCount = 0;
            for (ApiResult itemm : items) {
                if("压力大".equals(itemm.getPgjg()) || "超载".equals(itemm.getPgjg())
                        || "超标".equals(itemm.getPgjg()) || "健康度低".equals(itemm.getPgjg())) {
                    pgCount++;
                }
                if("变化趋差".equals(itemm.getZx())) {
                    zxCount++;
                }
                if("红色预警区".equals(itemm.getYjjg())) {
                    yjCount++;
                }
            }
            if(pgTitle != null) {
                result.setPgjg(new StringBuilder(pgTitle).append(pgCount).append("个").toString());
            }
            if(zxTitle != null) {
                result.setZx(new StringBuilder(zxTitle).append(zxCount).append("个").toString());
            }
            if(yjTitle != null) {
                result.setYjjg(new StringBuilder(yjTitle).append(yjCount).append("个").toString());
            }
        }
    }
    /**
     * @作者: 林楷
     * @日期: 2021/10/28
     * @描述: 返回资源环境承载力-综合监管模型结果
     */
    @Data
    public class ApiResult{
        private String pgjg = "-"; //评估结果
        private String zx = "-"; //指向
        private String yjjg = "-"; //预警结果
        private String parentCode; //父级编码

        private String groupItemCode;
        private String groupItemName;
        private String groupItemLevelName;
        private Object pgStatisticInformation;
        private Object zxStatisticInformation;
        private Object yjStatisticInformation;

        private List<ApiResult> childrens;
    }
}